package com.chasing.baseframe.db.manager;

import com.chasing.baseframe.MyApplication;
import com.chasing.baseframe.db.MyDatabase;
import com.chasing.baseframe.db.dao.FileDownloadCacheDao;
import com.chasing.baseframe.db.entity.FileDownloadCacheEntity;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class FileDownloadCacheManager {
    private FileDownloadCacheDao mDao;

    private FileDownloadCacheManager() {
        mDao = MyDatabase.getInstance(MyApplication.INSTANCE).fileDownloadCacheDao();
    }

    private static class InstanceHolder {
        static final FileDownloadCacheManager INSTANCE = new FileDownloadCacheManager();
    }

    public static FileDownloadCacheManager getInstance() {
        return InstanceHolder.INSTANCE;
    }

    public void save(FileDownloadCacheEntity entity) {
        mDao.insert(entity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
    }

    public void getByUrl(String url, Consumer<List<FileDownloadCacheEntity>> consumer) {
        mDao.getCacheByUrl(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(error -> consumer.accept(new ArrayList<>()))
                .subscribe(consumer);
    }

    public void delete(FileDownloadCacheEntity entity) {
        mDao.delete(entity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
    }

}
